package cn.com.headfree.util;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public class CookieUtil {
    private static final Logger LOG = LogManager.getLogger(CookieUtil.class);

    //保存cookie时的cookieName
    private final static String cookieDomainName = "cn.humanmanageding";

    //加密cookie时的网站自定码
    private final static String webKey = "humanmanageding";

    //设置cookie有效期是一个小时，根据需要自定义
    private final static long cookieMaxAge = 60 * 60;

    //保存Cookie到客户端--------------------------------------------------------------------------------------------------------
    //在filter中被调用
    //传递进来的首个code值进行保存以便与登录人对应
    public static void saveCookie(String code, HttpServletResponse response) {
        //cookie的有效期
        long validTime = System.currentTimeMillis() + (cookieMaxAge * 1000);
        //MD5加密用户详细信息
        String cookieValueWithMd5 =getMD5(code + ":" + validTime + ":" + webKey);
        //将要被保存的完整的Cookie值
        String cookieValue = code + ":" + validTime + ":" + cookieValueWithMd5;
        //再一次对Cookie的值进行BASE64编码
        String cookieValueBase64 = new String(Base64.encode(cookieValue.getBytes()));
        //开始保存Cookie
        Cookie cookie = new Cookie(cookieDomainName, cookieValueBase64);
        //存半个小时(这个值应该大于或等于validTime)
        cookie.setMaxAge(60 * 1);
        //cookie有效路径是根目录
        cookie.setPath("/human-manage-ding");
        LOG.info("===============cookie为===================:"+cookie);
        //向客户端写入
        response.addCookie(cookie);
    }

    //读取Cookie--------------------------------------------------------------------------------------------
    public static String readCookieAndLogon(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException,UnsupportedEncodingException{
        //根据cookieName取cookieValue
        Cookie cookies[] = request.getCookies();
        String cookieValue = null;
        if(cookies!=null){
            for(int i=0;i<cookies.length;i++){
                if (cookieDomainName.equals(cookies[i].getName())) {
                    cookieValue = cookies[i].getValue();
                    LOG.info("================cookieValue==================="+cookieValue);
                    break;
                }
            }
        }
        //如果cookieValue为空,返回,
        if(cookieValue==null){
            return null;
        }
        //如果cookieValue不为空,才执行下面的代码
        //先得到的CookieValue进行Base64解码
        String cookieValueAfterDecode = new String (Base64.decode(cookieValue),"utf-8");
        //对解码后的值进行分拆,得到一个数组,如果数组长度不为3,则cookie失效
        String cookieValues[] = cookieValueAfterDecode.split(":");
        String code = "";
        if(cookieValues.length==3){
            code = cookieValues[0];
        }
        //判断是否在有效期内,过期就删除Cookie
        long validTimeInCookie = new Long(cookieValues[1]);
        if(validTimeInCookie < System.currentTimeMillis()){
            //删除Cookie
            clearCookie(response);
            return null;
        }
        return code;
    }

    //清除Cookie------------------------------------------------------------
    public static void clearCookie( HttpServletResponse response){
        Cookie cookie = new Cookie(cookieDomainName, null);
        cookie.setMaxAge(0);
        cookie.setPath("/human-manage-ding");
        response.addCookie(cookie);
    }

    //获取Cookie组合字符串的MD5码的字符串----------------------------------------------------------------------------
    public static String getMD5(String value) {
        String result = null;
        try{
            byte[] valueByte = value.getBytes();
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(valueByte);
            result = toHex(md.digest());
        } catch (NoSuchAlgorithmException e2){
            e2.printStackTrace();
        }
        return result;
    }

    //将传递进来的字节数组转换成十六进制的字符串形式并返回
    private static String toHex(byte[] buffer){
        StringBuffer sb = new StringBuffer(buffer.length * 2);
        for (int i = 0; i < buffer.length; i++){
            sb.append(Character.forDigit((buffer[i] & 0xf0) >> 4, 16));
            sb.append(Character.forDigit(buffer[i] & 0x0f, 16));
        }
        return sb.toString();
    }

    public static String getCookie(HttpServletRequest request, String key) {
        Cookie[] cookies = request.getCookies();
        String value = null;
        if (cookies != null) {
            Cookie[] var6 = cookies;
            int var5 = cookies.length;

            for(int var4 = 0; var4 < var5; ++var4) {
                Cookie ck = var6[var4];
                if (ck.getName().trim().equals(key)) {
                    value = ck.getValue();
                    break;
                }
            }
        }

        return value;
    }
}

